/*****************************************************************************************
 **  Author:COCO 2022
 *****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
import { chunkArray, getDatakey } from '@/uitils/utils'
import { formatTimeStamp } from '@/uitils/dateFormatUtil'

let extension = {
  data() {
    return {
      // newDetailData: [],
      customer: [],
      currentRow: null,
    }
  },
  components: {
    //查询界面扩展组件
    gridHeader: '',
    gridBody: '',
    gridFooter: '',
    //新建、编辑弹出框扩展组件
    modelHeader: '',
    modelBody: '',
    modelFooter: '',
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: { view: [], box: [], detail: [] }, //扩展的按钮
  methods: {
    //下面这些方法可以保留也可以删除
    onInit() {
      //框架初始化配置前，
      //示例：在按钮的最前面添加一个按钮
      //   this.buttons.unshift({  //也可以用push或者splice方法来修改buttons数组
      //     name: '按钮', //按钮名称
      //     icon: 'el-icon-document', //按钮图标vue2版本见iview文档icon，vue3版本见element ui文档icon(注意不是element puls文档)
      //     type: 'primary', //按钮样式vue2版本见iview文档button，vue3版本见element ui文档button
      //     onClick: function () {
      //       this.$Message.success('点击了按钮');
      //     }
      //   });
      //示例：设置修改新建、编辑弹出框字段标签的长度
      // this.boxOptions.labelWidth = 150;
      //显示序号(默认隐藏)
      let { permission } = this.$store.getters.getPermission(
        '/Ware_DeliveryOrder'
      )
      this.columnIndex = true

      this.detailOptions.buttons.forEach((item) => (item.hidden = true))
      this.editFormOptions[0][0].extra = {
        render: (h, scope) => {
          return (
            <el-button
              disabled={this.currentAction == 'update' ? true : false}
              type="success"
              plain
              onClick={async () => {
                let { DeliveryOrderCode } = this.editFormFields
                if (!DeliveryOrderCode)
                  return this.$message.warning('请填写销售订单号')
                let res = await this.http.get(
                  `/api/Production_SalesOrderList/getProductByOrder?salesOrderCode=${DeliveryOrderCode}`,
                  null,
                  true
                )
                if (res.status) {
                  let detailData = this.$refs.detail.rowData
                  if (detailData.length == 0) {
                    res.data.forEach((item) => {
                      let {
                        deliveryOrderCode: DeliveryOrderCode,
                        outQnty: OutQnty,
                        productCode: ProductCode,
                        productName: ProductName,
                        type: Type,
                        stockQty,
                        qty: QntyMan,
                      } = item
                      detailData.push({
                        DeliveryOrderCode,
                        ProductCode,
                        ProductName,
                        OutQnty,
                        Type,
                        stockQty,
                        QntyMan,
                      })
                    })
                  }
                } else {
                  this.$message.error(res.message)
                }
              }}
            >
              查 询
            </el-button>
          )
        },
      }
      this.editFormOptions[1] = [
        {
          title: '出库人',
          field: 'OutMan',
          required: true,
        },
      ]
      this.editFormOptions[2] = [
        {
          title: '出库日期',
          field: 'CreateDate',
          required: true,
          type: 'datetime',
        },
      ]
      this.editFormOptions[3] = [
        {
          title: '客户名称',
          field: 'Client',
          required: true,
          type: 'select',
          dataKey: 'customers',
          // render: (h, { row }) => {
          //   return (
          //     <el-select
          //       v-model={this.editFormFields.Client}
          //       style={{ width: '100%' }}
          //     >
          //       {this.customer.map((item) => {
          //         return <el-option label={item.CusCode} value={item.CusCode} />
          //       })}
          //     </el-select>
          //   )
          // },
        },
      ]
      // console.log(this.editFormOptions);

      this.boxButtons.forEach((item) => {
        if (item.value == 'save') {
          item.onClick = async () => {
            try {
              let SelectedData =
                this.$refs.detail.$refs.table.getSelectionRows()
              if (SelectedData.length == 0)
                return this.$message.warning('请勾选要出库的数据')
              let {
                OutMan: outMan,
                Client: client,
                CreateDate: createDate,
              } = this.editFormFields
              if (!outMan) return this.$message.warning('请输入出库人')
              if (!client) return this.$message.warning('请输入客户编码')
              if (!createDate) return this.$message.warning('请输入出库日期')
              SelectedData = SelectedData.map((item) => {
                if (!item.Qnty) throw new Error('请输入出库数量')
                return {
                  deliveryOrderDetailID: 0,
                  deliveryOrderID: 0,
                  deliveryOrderCode: item.DeliveryOrderCode,
                  productCode: item.ProductCode,
                  productName: item.ProductName,
                  specification: '',
                  lotNo: '',
                  type: item.Type,
                  outType: '',
                  qnty: Number(item.Qnty),
                  outQnty: item.OutQnty,
                  qntyMan: item.QntyMan,
                  outMan,
                  postID: '',
                  state: 0,
                  remake: '',
                  createDate,
                  createID: 0,
                  creator: '',
                  modifier: '',
                  modifyDate: '',
                  modifyID: 0,
                  client: '',
                }
              })

              let params = {
                deliveryMan: {
                  deliveryOrderID: 0,
                  deliveryOrderCode: SelectedData[0].deliveryOrderCode,
                  productCode: '',
                  productName: '',
                  specification: '',
                  lotNo: '',
                  type: '',
                  outType: '',
                  qnty: 0,
                  outQnty: 0,
                  postID: '',
                  outMan: '',
                  state: 0,
                  remake: '',
                  createDate: '',
                  createID: 0,
                  creator: '',
                  modifier: '',
                  modifyDate: '',
                  modifyID: 0,
                  client,
                },
                deliveryDetail: SelectedData,
              }
              // this.print(params)
              // console.log(params)
              let res = await this.http.post(
                '/api/Ware_DeliveryOrder/DeliveryOrderAdd',
                params,
                true
              )
              if (res.status) {
                this.$message.success(res.message)
                this.clearForm()
                this.$refs.detail.rowData = []
                this.boxModel = false
                this.search()

                // try {
                //   await ElMessageBox.confirm('是否打印该出库单？', '提示', {
                //     confirmButtonText: '确认',
                //     cancelButtonText: '取消',
                //     type: 'warning',
                //   })
                // } catch (err) {
                //   console.log('cancel')
                // }
              } else {
                this.$message.error(res.message)
              }
            } catch (error) {
              this.$message.error(error.message)
            }
          }
        }
      })

      this.boxButtons.push({
        name: '打 印',
        value: 'print',
        icon: 'el-icon-printer',
        onClick: () => {
          console.log('print')
          let deliveryDetail = this.$refs.detail.$refs.table.getSelectionRows()
          console.log(deliveryDetail);
          if (deliveryDetail.length === 0)
            return this.$message.error('请选择一条数据')

          this.print({
            deliveryMan: {
              ...this.editFormFields,
            },
            deliveryDetail: [...deliveryDetail],
          })
        },
      })

      this.columns.unshift({
        title: '操作',
        field: 'action',
        width: 220,
        render: (h, { row, column }) => {
          let dom1 = ''
          let dom2 = ''
          if (permission.includes('checkOutRecords')) {
            // if (row.State == 0) {
            let dom3 = ''
            if (row.State == 0) {
              dom3 = (
                <div>
                  <i class="el-icon-edit"></i>
                  编辑待出库数量
                </div>
              )
            } else {
              dom3 = (
                <div>
                  <i class="el-icon-view"></i>
                  查看出库记录
                </div>
              )
            }
            dom1 = (
              <el-link
                type="primary"
                underline={false}
                onClick={async () => {
                  console.log(row);
                  // await this.getDetailData(row)
                  this.detailOptions.url = `/api/Ware_DeliveryOrder/selectDeliveryOrderlist?DeliveryOrderCode=${row.DeliveryOrderCode}`
                  this.currentRow = row
                  this.linkData(row, column)
                }}
              >
                {dom3}
              </el-link>
            )
            // }
          }

          if (permission.includes('CheckAndRelease')) {
            if (row.State == 0) {
              dom2 = (
                <el-link
                  type="primary"
                  underline={false}
                  style="margin-left: 10px"
                  onClick={async () => {
                    // DeliveryOrderCode
                    const res = await this.http.post(
                      '/api/Ware_DeliveryOrder/DeliveryOrderOutInput?Ordercode=' +
                        row.DeliveryOrderCode,
                      null,
                      true
                    )
                    if (res.status) {
                      this.$message.success('审核成功')
                      this.search()
                    } else {
                      this.$message.error(res.message)
                    }
                  }}
                >
                  <i class="el-icon-box"></i>
                  审核出库
                </el-link>
              )
            }
          }

          return h('div', [dom1, dom2])
        },
      })

      this.$nextTick(() => {
        getDatakey(['customers']).then((res) => {
          this.customer = res[0].data
          console.log('customer', this.customer)
        })
      })
    },
    onInited() {
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      // this.detailOptions.columns.some(column=>{
      //   console.log(column);
      //   if(column.field == "Qnty") {
      //     column.onKeyPress = ({Qnty, LotNo, DeliveryOrderDetailID}) => {
      //       let qnty = Number(Qnty)
      //       if(qnty !== qnty) {
      //         this.$message.error('请输入数字')
      //         return
      //       }
      //     }
      //     return true
      //   }
      // });
      this.detailOptions.columns.push(
        ...[
          {
            title: '单位',
            field: 'Unit',
          },
          {
            title: '操作',
            field: 'action',
            width: 150,
            render: (h, { row, column, index }) => {
              let dom1 = ''
              let dom2 = ''

              dom1 = (
                <el-link
                  underline={false}
                  type="primary"
                  onClick={async () => {
                    let qnty = Number(row.Qnty)
                    if (qnty !== qnty) {
                      this.$message.error('请输入数字')
                      return
                    }
                    const { Qnty, LotNo, DeliveryOrderDetailID } = row
                    const res = await this.http.post(
                      `/api/Ware_DeliveryOrder/DeliveryOrderUpdate?id=${DeliveryOrderDetailID}&LotNo=${LotNo}&qnty=${Qnty}`,
                      null,
                      true
                    )
                    if (res.status) {
                      this.$message.success('修改成功')
                    } else {
                      this.$message.error(res.message)
                    }
                  }}
                >
                  <i class="el-icon-edit-outline"></i>
                  保存编辑
                </el-link>
              )

              dom2 = (
                <el-link
                  underline={false}
                  type="primary"
                  style={{ marginLeft: '10px' }}
                  onClick={async () => {
                    const { DeliveryOrderCode, DeliveryOrderDetailID } = row
                    const res = await this.http.post(
                      `/api/Ware_DeliveryOrder/DeliveryOrderDelete?id=${DeliveryOrderDetailID}&code=${DeliveryOrderCode}`,
                      null,
                      true
                    )
                    if (res.status) {
                      this.$message.success('删除成功')
                      this.linkData(this.currentRow, column)
                    } else {
                      this.$message.error(res.message)
                    }
                  }}
                >
                  <i class="el-icon-delete"></i>
                  删除
                </el-link>
              )

              return h('div', [dom1, dom2])
            },
          },
        ]
      )
    },
    searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      return true
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      return true
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return true
    },
    rowClick({ row, column, event }) {
      //查询界面点击行事件
      // this.$refs.table.$refs.table.toggleRowSelection(row); //单击行时选中当前行;
    },
    modelOpenAfter(row) {
      //点击编辑、新建按钮弹出框后，可以在此处写逻辑，如，从后台获取数据
      //(1)判断是编辑还是新建操作： this.currentAction=='Add';
      //(2)给弹出框设置默认值
      //(3)this.editFormFields.字段='xxx';
      //如果需要给下拉框设置默认值，请遍历this.editFormOptions找到字段配置对应data属性的key值
      //看不懂就把输出看：console.log(this.editFormOptions)
      console.log(this.currentAction)

      if (this.currentAction == 'update') {
        // this.boxButtons[0].hidden = true

        this.boxButtons.forEach((item) => {
          if (item.value == 'print') {
            item.hidden = false
          }
          if (item.value == 'save') {
            item.hidden = true
          }
        })

        this.detailOptions.columns.forEach((column) => {
          if (column.field == 'OutQnty') {
            column.hidden = true
          }
          if (column.field == 'CreateDate') {
            column.hidden = false
          }
          if (column.field == 'OutMan') {
            column.hidden = true
          }
          if (column.field == 'action') {
            column.hidden = false
          }
          if (column.field == 'Unit') {
            column.hidden = false
          }
          if (column.field == 'action') {
            if (row.State == 1) {
              column.hidden = true
            }
          }
        })

        // this.editFormOptions.forEach((x) => {
        //   x.forEach((item) => {
        //     if (item.field == 'Client') {
        //       item.hidden = true
        //     }
        //   })
        // })
      }
      if (this.currentAction == 'Add') {
        this.boxButtons.forEach((item) => {
          if (item.value == 'print') {
            item.hidden = true
          }
          if (item.value == 'save') {
            item.hidden = false
          }
        })
        this.detailOptions.columns.forEach((column) => {
          if (column.field == 'OutQnty') {
            column.hidden = false
          }
          if (column.field == 'CreateDate') {
            column.hidden = true
          }
          if (column.field == 'OutMan') {
            column.hidden = true
          }
          if (column.field == 'action') {
            column.hidden = true
          }
          if (column.field == 'Unit') {
            column.hidden = true
          }
          if (column.field == 'action') {
            column.hidden = true
          }
        })

        this.editFormOptions.forEach((x) => {
          x.forEach((item) => {
            if (item.field == 'Client') {
              item.hidden = false
            }
          })
        })
      }
    },
    clearForm() {
      for (let key in this.editFormFields) {
        this.editFormFields[key] = ''
      }
    },
    searchDetailAfter(data) {
      // console.log(data)
      this.$nextTick(() => {
        this.$refs.detail.rowData = data.map((item) => {
          return {
            DeliveryOrderDetailID: item.deliveryOrderDetailID,
            LotNo: item.lotNo,
            DeliveryOrderCode: item.deliveryOrderCode,
            DeliveryOrderMoCode: item.deliveryOrderMoCode,
            CreateDate: item.createDate,
            OutMan: item.outMan,
            ProductCode: item.productCode,
            ProductName: item.productName,
            Qnty: item.qnty,
            QntyMan: item.qntyMan,
            Specification: item.specification,
            Type: item.type,
            Unit: item.unit,
          }
        })
        // console.log(this.$refs.detail.rowData)
        this.editFormFields.CreateDate = this.$refs.detail.rowData[0].CreateDate
        this.editFormFields.OutMan = this.$refs.detail.rowData[0].OutMan
        this.editFormFields.Client = this.currentRow.Client
      })

      return true
    },
    // async getDetailData({ DeliveryOrderCode }) {
    //   let res = await this.http.post(
    //     `/api/Ware_DeliveryOrder/selectDeliveryOrderlist?DeliveryOrderCode=${DeliveryOrderCode}`,
    //     null,
    //     true
    //   )
    //   this.newDetailData = res.data
    // },
    async print(data) {
      console.log(data)
      let outMan = data.deliveryDetail[0].OutMan
      let client = data.deliveryMan.Client
      // let deliveryOrderCode = data.deliveryMan.DeliveryOrderCode
      let sendDate = formatTimeStamp(data.deliveryMan.CreateDate, 'yyyy-MM-dd')
      let KMSCode = sendDate.split('-').join('')
      const res = await this.http.get(`/api/Production_WorkOrder/GetCustomer?CusCode=${client}`, null, true)
      const { cusName, phoneNo, address} = res
      // console.log(res);
      let printWindow = window.open('', '_blank')
      printWindow.document.open()
      let style = `<style>
                      .title {
                        text-align:center;
                        position: relative;
                      }

                      .header {
                        display: flex;
                        margin-bottom: 20px;
                        font-size: 14px;
                      }

                      .t_head {
                        flex: 1;
                      }

                      .t_head .th_item {
                        display: flex; 
                        list-style: none;
                      }

                      .t_head .th_item .th_title {
                        flex: 1; 
                        display: flex;
                        text-align: left;
                        text-indent: 20;
                      }

                      .th_title .th_title_space {
                        display: inline-block; 
                      }

                      #qrcodeImg {
                        width: 100px; 
                        height: 100px;
                        margin-left: 10px;
                      }

                      .grid_table {
                        width: 100%; 
                        border: 1px solid #000; 
                        border-collapse: collapse;
                        font-size: 12px;
                      }

                      th {
                        border: 1px solid black;  
                      }

                      .grid_table tr td {
                        border: 1px solid black;
                      }

                      .grid_table tbody {
                        text-align:center;
                      }

                      .footer {
                        display: flex; 
                        justify-content: 
                        space-between; 
                        list-style: none;
                        font-size: 12px;
                      }

                      .footer_space {
                        margin-left: 30px;
                        display: inline-block; 
                        width: 100px; 
                        border-bottom: 1px solid #000;
                      }

                      .version {
                        margin-top: 15px;
                      }

                      .kms {
                        text-align: right;
                      }
                    </style>`

      let title = `<div>
                        <h2 class="title">昆山鸿永峻精密五金电子科技有限公司</h2>
                        <h3 class="title">送货单</h3>
                        <div class="kms">KMS${KMSCode}</div>
                    </div>`

      let header = `<div class="header">
                        <div class="t_head">
                          <ul class="th_item">
                            <li class="th_title">
                              客户名称:
                              <span class="th_title_space" style="margin-left: 5px;">${cusName}</span>
                            </li>

                            <li class="th_title">
                              地址:
                              <span class="th_title_space" style="margin-left: 5px;">${address || ''}</span>
                            </li>
                          </ul>
                          
                          <ul class="th_item">
                            <li class="th_title">
                              送货日期:
                              <span class="th_title_space" style="margin-left: 5px;">${sendDate}</span>
                            </li>
                            <li class="th_title">
                              电话/传真:
                              <span class="th_title_space" style="margin-left: 5px;">${phoneNo || ''}</span>
                            </li>
                          </ul>
                        </div>
                          
                    </div>`

      let footer = `<div>
                    <ul class="footer"> 
                        <li>
                          制单:
                          <span class="footer_space">${outMan}</span>
                        </li>
                        <li>
                          品质部:
                          <span class="footer_space"></span>
                        </li>
                        <li>
                          仓管:
                          <span class="footer_space"></span>
                        </li>
                        <li>
                          审核:
                          <span class="footer_space"></span>
                        </li>
                        <li>
                          客户回签:
                          <span class="footer_space"></span>
                        </li>
                    </ul>
                  <div>`

      let result = chunkArray(data.deliveryDetail, 24)
      console.log(result)
      let body = ``
      let total = 0
      result.forEach((arr) => {
        let main = ``
        arr.forEach((item, index) => {
          total += item.Qnty
          main += `<tr style="border: 1px dotted black;">
          <td>${index + 1}</td>
          <td>${item.DeliveryOrderMoCode}</td>
          <td>${item.ProductName}</td>
          <td>${item.Specification}</td>
          <td>${item.Unit}</td>
          <td>${item.Qnty}</td>
          <td></td>
        </tr>`
        })

        body += `<table class="grid_table">
          <thead>
            <tr>
              <th>序号</th>
              <th>采购单号</th>
              <th>品名</th>
              <th>规格</th>
              <th>单位</th>
              <th>数量</th>
              <th>备注</th>
            </tr>
          </thead>
          <tbody>
            ${main}
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td>合计</td>
              <td>${total}</td>
              <td></td>
            </tr>
            <tr>
              <td colspan="7">注：本单作为货物收据，敬请妥善保管。</td>
            </tr>
          </tbody>
        </table>${footer}`
      })

      // let sscript = ` <script src="/qrcode.min.js" type="application/javascript"></script>
      //                 <script>
      //                   window.addEventListener("DOMContentLoaded", ()=> {
      //                     const qrcodeImgEl = document.getElementById('qrcodeImg')
      //                     qrcodeImgEl.innerHTML = ''
      //                     let qrcode = new QRCode(qrcodeImgEl, {
      //                                             width: 100,
      //                                             height: 100,
      //                                             colorDark: '#000000',
      //                                             colorLight: '#ffffff',
      //                                             correctLevel: QRCode.CorrectLevel.H,
      //                                   })
      //                     qrcode.makeCode('${deliveryOrderCode}')
      //                   })
      //                 </script>`
      printWindow.document.write(
        `<html><head><title>Print</title>${style}</head><body>`
      )
      printWindow.document.write(title)
      printWindow.document.write(header)
      printWindow.document.write(body)
      printWindow.document.write(`</body></html>`)
      printWindow.document.close()
      setTimeout(() => {
        printWindow.print()
        printWindow.close()
      }, 100)
    },
  },
}
export default extension
